import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Klientobsluga {

	private Socket socket ;
	Message m ;
	private ObjectInputStream inStream; 
	private ObjectOutputStream outStream; 
	
	public Klientobsluga(int port)
	{
		System.out.println("rozpoczynam inizcjaliazje") ;
		netInit(port) ;
		
		System.out.println("koncze inizcjaliazje") ;
	}
	public void netInit(int port) {
		
    	 try {
			socket = new Socket("localhost", port);

		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
	
	public Message getMessage() {
		try {
			inStream = new ObjectInputStream(socket.getInputStream()); 
		} catch(Exception e) { System.out.println(e.getMessage()); }
		Message m = null ;
		
		try {
			m = (Message) inStream.readObject();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return m;
	}

	protected void handleMessage(Message m) {
		
		System.out.println("Przetwarzam wiadomosc od serwera danych : " +m.getCommand()) ;
		
	}
	
	public void sendMessage(Message m) { //wysylanie z serializacja 		
		try {
			outStream = new ObjectOutputStream(socket.getOutputStream()); 
		} catch(Exception e) { System.out.println(e.getMessage()); }
		
			System.out.println("Sending message to " + socket.getPort());
			try {
				outStream.writeObject(m);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public void connectionClose()
	{
		try {
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

